﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using ForumsBrowser.ObjectGateway;
using ForumsBrowser.Common;
using ForumsBrowser.BusinessObjects;

namespace ForumsBrowser
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ForumView forumView;
        ThreadViewer threadViewer;
        MiniView miniView = new MiniView();

        private bool _isMiniView;

        public bool IsMiniView
        {
            get { return _isMiniView; }
            set
            {
                if (Configuration.IsMiniViewEnabled)
                {
                    bool changed = _isMiniView != value;
                    _isMiniView = value;
                    if (changed && _isMiniView)
                        SwitchToMiniView();
                    else if (changed)
                        SwitchToMainView();
                }
            }
        }
        
        
        public MainWindow()
        {
            InitializeComponent();
            LastState = WindowState.Normal;
        }

        private void forumView_ThreadSelected(object sender, ThreadSelectedEventArgs e)
        {
            this.IsMiniView = false;
            threadViewer.ViewThread(e.Thread);
            closeListBox.Begin(topgridpanel);
        }

        protected void ForumSelected(object sender, ForumSelectedEventArgs e)
        {
            forumView.BindThreads(e.ForumShortName, true);
        }

        protected void ForumSubscribed(object sender, ForumSubscribeEventArgs e)
        {
            selectedForums.AddForum(e.Forum);
        }

        protected void ForumUnsubscribed(object sender, ForumSubscribeEventArgs e)
        {
            selectedForums.RemoveForum(e.Forum);
        }

        protected void ViewSelectedForums(object sender, ViewSelectedForumsEventArgs e)
        {
            forumView.BindThreads(e.SelectedForums.Select(f => f.ShortName));
        }

        private void availableForums_FinishedLoading(object sender, ViewSelectedForumsEventArgs e)
        {
            e.SelectedForums.ToList().ForEach(f => selectedForums.SelectedForums.AddUnique(f, (a, b) => a.ShortName == b.ShortName));
        }

        private void forumView_ViewLastPost(object sender, ThreadSelectedEventArgs e)
        {
            try
            {
                if (e.Thread.Messages.Count == 0)
                    e.Thread = Gateway.ThreadGet(e.Thread.XmlUrl);

                threadViewer.ViewMessage(e.Thread.Messages.LastOrDefault(), true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Oops! I won't be able to see this thread in thread view.  I'll open it up for you in the web browser instead." +
                    "\n\nIf you want this to be looked at, post an issue at http://forumsbrowser.codeplex.com/ and reference the following URL.\n\n" + e.Thread.Url);
                threadViewer.Browse(e.Thread);        
                ErrorHandler.HandleError(ex);
            }
            closeListBox.Begin(topgridpanel);
        }

        private void forumView_Browse(object sender, ThreadSelectedEventArgs e)
        {
            try
            {
                threadViewer.Browse(e.Thread);
                closeListBox.Begin(topgridpanel);
            }
            catch (Exception ex)
            {
                ErrorHandler.HandleError(ex);
            }
        }

        private void userSettings_Done(object sender, EventArgs e)
        {
            userSettingsExpander.IsExpanded = false;
            if (Configuration.Culture.Name != userSettings.SelectedCulture.Name)
            {
                Configuration.Culture = userSettings.SelectedCulture;
                availableForums.BindData(true);
                selectedForums.ClearSelectedForums();
            }

            if (Configuration.IsMiniViewEnabled != userSettings.IsMiniViewEnabled)
                Configuration.IsMiniViewEnabled = userSettings.IsMiniViewEnabled;

            if (Configuration.MiniViewMinHeight != userSettings.MiniViewMinHeight)
                Configuration.MiniViewMinHeight = userSettings.MiniViewMinHeight;
        }

        private void userSettings_Cancel(object sender, EventArgs e)
        {
            userSettingsExpander.IsExpanded = false;
        }

        private void SwitchToMiniView()
        {
            if (Configuration.IsMiniViewEnabled)
            {
                this.topgridpanel.Children.Remove(forumView);
                forumView.Background = Brushes.Transparent;
                miniView.SetForumView(forumView);
                miniView.Show();
                this.Hide();
                miniView.FadeOut();
            }
        }

        private void SwitchToMainView()
        {
            if (Configuration.IsMiniViewEnabled)
            {
                miniView.Hide();
                this.topgridpanel.Children.Add(miniView.RemoveForumView());
                this.Show();
                this.WindowState = LastState;
            }
        }

        private void mainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            forumView = (ForumView)Resources["forumView"];
            threadViewer = (ThreadViewer)Resources["threadViewer"];

            this.topgridpanel.Children.Add(forumView);
            this.bottomPanel.Children.Add(threadViewer);
            miniView.Closing += MiniView_Closing;

           var forums = Gateway.AvailableForumsGet(false).SelectMany(f => f.Forums).Where(f => f.IsSelected).Select(f => f.ShortName);
           forumView.BindThreads(forums);
        }

        private void MiniView_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.IsMiniView = false;
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            miniView.Closing -= MiniView_Closing;
            miniView.Close();
            base.OnClosing(e);
        }

        public WindowState LastState
        {
            get; private set; 
        }

        private void mainWindow_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
                this.IsMiniView = true;
            else
                LastState = this.WindowState;
        }
    }
}
